package me.pplay.playtalk.adapter;


import java.io.File;
import java.util.List;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.activity.ChatConversationActivity;
import me.pplay.playtalk.bean.ChattingRecord;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.holder.ChatConversatoinHolder;
import me.pplay.playtalk.net.HttpUtil;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import me.pplay.playtalk.util.AsyncImageLoader;
import me.pplay.playtalk.util.AsyncImageLoader.ImageCallback;
import me.pplay.playtalk.util.DateParseUtil;
import me.pplay.playtalk.util.fileUtil.FileUtil;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ChatConversationAdapter extends BaseAdapter {
	private Context mContext;
	private LayoutInflater inflater;
	private List<ChattingRecord> chatList;
	private AsyncImageLoader imageLoader;
	private MediaPlayer mediaPlayer;
	private TpChat tpChat;
	private int sdkVertion = -1;
	private Handler handler;
	
	public ChatConversationAdapter(Context context,  List<ChattingRecord> chatList, AsyncImageLoader imageLoader, int sdkVersion, Handler handler){
		this.mContext			= context;
		this.chatList			= chatList;
		this.imageLoader		= imageLoader;
		this.inflater			= (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
		this.sdkVertion			= sdkVersion;
		this.tpChat				= ((ApplicationTrans)mContext.getApplicationContext()).getTpChat();
		this.handler			= handler;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return chatList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return chatList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ChatConversatoinHolder holder;
		final ChattingRecord chat			= chatList.get(position);
		if(chat == null)
			return null;
//		if(convertView == null || (convertView != null && convertView.getTag(chat.skyid) == null)){
			holder 	= new ChatConversatoinHolder();
			if(Globals.skyid == chat.skyid){
				convertView			= inflater.inflate(R.layout.list_say_me_item, null);
			}else{
				convertView			= inflater.inflate(R.layout.list_say_he_item, null);
			}
			holder.layout_bg		= (LinearLayout)convertView.findViewById(R.id.layout_bg);
			holder.icon				= (ImageView)convertView.findViewById(R.id.icon);
			holder.name				= (TextView)convertView.findViewById(R.id.msg_name);
			holder.time				= (TextView)convertView.findViewById(R.id.msg_date);
//			convertView.setTag(chat.skyid, holder);
//		}else{
//			holder					= (ChatConversatoinHolder)convertView.getTag(chat.skyid);
//		}
		
		//////////////holder.layout_bg 根据设置   设置背景////////if(true){holder.layout_bg.setBackgroundDrawable(d)}else{}
		holder.name.setText(chat.name);
		holder.time.setText(DateParseUtil.getTimeText(Long.parseLong(chat.time)));
		setImageIcon(holder.icon, chat.skyid);
		final String type 		= chat.type;
		String content			= chat.content;
		
		
		if(type.equals("0")){
			holder.content		= (TextView)convertView.findViewById(R.id.msg_detail);
			holder.content.setVisibility(View.VISIBLE);
			holder.content.setText(FileUtil.strToImage(content, mContext));
		}else{
			holder.layout_media	= (LinearLayout)convertView.findViewById(R.id.layout_media);
			holder.media		= (ImageView)convertView.findViewById(R.id.media);
			holder.media_detail	= (TextView)convertView.findViewById(R.id.media_detail);
			holder.layout_progress = (RelativeLayout)convertView.findViewById(R.id.layout_progress);
			holder.progress		= (ProgressBar)convertView.findViewById(R.id.progress);
			holder.closeDownBtn	= (ImageButton)convertView.findViewById(R.id.closeDownBtn);
			
			holder.layout_media.setVisibility(View.VISIBLE);
			
			//获取缩略图
			if(Globals.skyid == chat.skyid){
				if(!FileUtil.isExistFile(content) || sdkVertion < 8){
					setDefaultIcon(holder.media, chat.type);
				}else{ //获取缩略图
					if(chat.type.equals("1")){
						getImageThumbnail(chat.content, 60, 60, new DataCallBack() {
							
							@Override
							public void Callback(int result, RspData resultdata, Object obj) {
								// TODO Auto-generated method stub
								if(obj != null)
									holder.media.setImageBitmap((Bitmap)obj);
								else
									holder.media.setBackgroundResource(R.drawable.default_pic);	
							}
						});
					}else if(chat.type.equals("2")){
						getVideoThumbnail(chat.content, 60, 60, MediaStore.Images.Thumbnails.MICRO_KIND, new DataCallBack(){

							@Override
							public void Callback(int result, RspData resultdata, Object obj) {
								if(obj != null)
									holder.media.setImageBitmap((Bitmap)obj);
								else
									holder.media.setBackgroundResource(R.drawable.default_video);	
							}
						});
					}
				}
				
				if(chat.type.equals("3"))
					holder.media.setBackgroundResource(R.drawable.default_message);	
			}else{
				if(chat.content == null || chat.content.equals("")){
					setDefaultIcon(holder.media, chat.type);
				}else{
					setImageIcon(holder.media, "http://" + tpChat.tp_chat_gethttpaddr_data(chat.server_id) + "/" + chat.content, type);
				}
			}
			
			
			
			//下载资源文件
			String filepath = "";
			if(Globals.skyid == chat.skyid)
				filepath				= content;
			else{
				filepath				= HttpUtil.getFilePath(chat, "http://" + tpChat.tp_chat_gethttpaddr_data(chat.server_id) + "/" + chat.fpath);
			}
			
			if(FileUtil.isExistFile(filepath)){ //上传
				if(type.equals("3")){ //录音
					holder.media.setOnClickListener(new TalkClick(filepath));
				}else{
					holder.media_detail.setVisibility(View.VISIBLE);
					holder.media_detail.setText(mContext.getString(R.string.view));
					holder.media_detail.setOnClickListener(new MediaDetailClick(filepath, type));
				}
			}else if(Globals.skyid != chat.skyid){
				holder.media_detail.setVisibility(View.VISIBLE);
				holder.media_detail.setText(mContext.getString(R.string.download));
				//下载
				if(chat.fpath != null){
					holder.media_detail.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							 chat.isDownd = true;
							 holder.layout_progress.setVisibility(View.VISIBLE);
							 HttpUtil.doGet(chat, tpChat, new DataCallBack() {
								
								@Override
								public void Callback(int result, RspData resultdata, Object obj) {
									if(result == HttpUtil.GET_FILE_OK){
										int progress = (Integer)obj;
										chat.progress = progress;
										holder.progress.setProgress((Integer)obj);
										if(progress == 100){
											 holder.layout_progress.setVisibility(View.GONE);
											 chat.isDownd = false;
											 handler.sendEmptyMessage(ChatConversationActivity.SETADAPTER);
										}
									}
								}
							});
						}
					});
				}
			}
			if(chat.isDownd){
				holder.layout_progress.setVisibility(View.VISIBLE);
				holder.progress.setProgress(chat.progress);
			}else{
				holder.layout_progress.setVisibility(View.GONE);
			}
			holder.closeDownBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					holder.layout_progress.setVisibility(View.GONE);
					if(chat.tpFile != null)
						chat.tpFile.tp_file_upload_stop();
					chat.isDownd 	= false;
					chat.progress 	= 0;
				}
			});
		}
		return convertView;
	}

	private void setDefaultIcon(final ImageView imageView, final String type){
		if(type.equals("1"))
			imageView.setBackgroundResource(R.drawable.default_pic);	
		else if(type.equals("2"))
			imageView.setBackgroundResource(R.drawable.default_video);
		else if(type.equals("3"))
			imageView.setBackgroundResource(R.drawable.default_message);	
	}
	
	private void setImageIcon(final ImageView imageView, final String imageUrl, String type){
		if(type != null)
			setDefaultIcon(imageView, type);
		Bitmap bitmap = imageLoader.loadBitmap(imageUrl, new ImageCallback() {
			
			@Override
			public void imageLoaded(Bitmap imageBitmap, String imageUrl) {
				if(imageBitmap != null)
					imageView.setImageBitmap(imageBitmap);
			}
		});
		if(bitmap != null)
			imageView.setImageBitmap(bitmap);
	}
	
	private void setImageIcon(final ImageView imageView, final int skyid){
		TPBuddyinfo buddyinfo 	= tpChat.tp_chat_getBuddyinfo(skyid);
		try {
			if(buddyinfo == null){
				imageView.setBackgroundResource(R.drawable.class.getDeclaredField("avatar0").getInt(mContext));
			}else{
				int avatar_sid 	= buddyinfo.getAvatar_sid();
				if(buddyinfo.getAvatar_fpath().equals("")){
					String name 	= "";
					if(avatar_sid == 0){
						name = buddyinfo.getSex() == 1?"avatar0":"avatarf";
					}else{
						name = "avatar"+avatar_sid;
					}
					imageView.setBackgroundResource(R.drawable.class.getDeclaredField(name).getInt(mContext));
				}else{
					setImageIcon(imageView, "http://" + tpChat.tp_chat_gethttpaddr_data(avatar_sid) + "/" + buddyinfo.getAvatar_fpath(), null);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	class MediaDetailClick implements OnClickListener{
		   String filePath 	= "";
		   String type		= "";
		   public MediaDetailClick(String filePath, String type){
			   this.filePath	= filePath;
			   if(type.equals("1")) //image
				   this.type		= "image/*";
			   else
				   this.type		= "video/*";
		   }
		
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();  
				intent.setAction(android.content.Intent.ACTION_VIEW);  
				intent.setDataAndType(Uri.fromFile(new File(filePath)), type);  
				mContext.startActivity(intent);
			}
	}
	
	
	
	class TalkClick implements OnClickListener{

		String filepath = "";
		public TalkClick(String path){
			filepath    = path;
		}
		
		@Override
		public void onClick(View v) {
			try{
				if(!FileUtil.isExistFile(filepath))
					return;

				if(mediaPlayer == null)
					mediaPlayer	= new MediaPlayer();
				if (mediaPlayer.isPlaying()){
					mediaPlayer.stop();
				}else{
					mediaPlayer.reset();
					mediaPlayer.setDataSource(filepath);
					mediaPlayer.prepare();
					mediaPlayer.start();
					mediaPlayer.setOnCompletionListener(new OnCompletionListener(){

						public void onCompletion(MediaPlayer mp){
							mediaPlayer.stop();
						}
					});
				}

			} catch (Exception e){
				e.printStackTrace();
			}
		}
	}
	
	
	
	/**
	 * 获取图片缩略图       2.2以上可以用
	 * imageThumbnail.setImageBitmap(getImageThumbnail(imagePath, 60, 60));  
	 * @param imagePath
	 * @param width
	 * @param height
	 * @return
	 */
	private void getImageThumbnail(String imagePath, int width, int height, DataCallBack callback) {  
	        Bitmap bitmap = null;  
	        BitmapFactory.Options options = new BitmapFactory.Options();  
	        options.inJustDecodeBounds = true;  
	        // 获取这个图片的宽和高，注意此处的bitmap为null  
	        bitmap = BitmapFactory.decodeFile(imagePath, options);  
	        options.inJustDecodeBounds = false; // 设为 false  
	        // 计算缩放比  
	        int h = options.outHeight;  
	        int w = options.outWidth;  
	        int beWidth = w / width;  
	        int beHeight = h / height;  
	        int be = 1;  
	        if (beWidth < beHeight) {  
	            be = beWidth;  
	        } else {  
	            be = beHeight;  
	        }  
	        if (be <= 0) {  
	            be = 1;  
	        }  
	        options.inSampleSize = be;  
	        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false  
	        bitmap = BitmapFactory.decodeFile(imagePath, options);  
	        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象  
	        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);  
	        callback.Callback(0, null, bitmap);
//	        return bitmap;  
	    } 
	
	/**
	 * 根据视频Uri地址取得指定的视频缩略图
	 * @param cr  
	 * @param uri  本地视频Uri标示
	 * @return 返回bitmap类型数据
	 * imageThumbnail.setImageBitmap(getImageThumbnail(imagePath, 60, 60));  
        videoThumbnail.setImageBitmap(getVideoThumbnail(videoPath, 60, 60,  
                MediaStore.Images.Thumbnails.MICRO_KIND))
	 */
	private void getVideoThumbnail(String videoPath, int width, int height, int kind, DataCallBack callback) {  
        Bitmap bitmap = null;  
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);  
        System.out.println("w"+bitmap.getWidth());  
        System.out.println("h"+bitmap.getHeight());  
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,  
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);  
        callback.Callback(0, null, bitmap);
    }  
}
